package com.gyms.activity;

import android.content.Intent;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.classic.okhttp.AppChangeUtils;
import com.classic.okhttp.Cons;
import com.classic.okhttp.services.IUserService;
import com.classic.okhttp.zmoumall.http.ObjectCallback;
import com.classic.okhttp.zmoumall.utils.MD5;
import com.classic.okhttp.zmoumall.utils.ToastUtil;
import com.gyms.R;
import com.gyms.base.MyAutoLayoutActivity;
import com.gyms.constant.Constants;
import com.gyms.manager.DataCenter;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.OnClick;
import constant.EventConstant;
import utils.ActivityStack;
import utils.DataUtil;
import utils.RegexUtils;
import utils.StringUtils;
import weight.PhoneEditText;
import weight.UiEvent;

import static com.gyms.R.id.tv_tips;

/**
 * Created by 小俞 on 2016/12/13 0013.
 */

public class LoginActivity extends MyAutoLayoutActivity {
    @BindView(R.id.et_phone)
    PhoneEditText etPhone;
    @BindView(R.id.et_password)
    PhoneEditText etPassword;
    @BindView(R.id.btn_login)
    Button btnLogin;
    @BindView(tv_tips)
    TextView tvTips;
    @BindView(R.id.yan_zhen)
    TextView yanZhen;

    private String phone;
    private String password;
    private boolean isToMain;//判断是否要跳转到主页

    private String mTempPhone;

    private String mFunction;//JS登录的回调函数

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_password_login;
    }

    @Override
    protected void initView() {
        initData();
        ActivityStack.getInstance().addActivity(this);
        setTitle("密码登录");
        setBack();
        createLoadingView("登录中", true);
        isToMain = getIntent().getBooleanExtra("isToMain", false);
        mTempPhone=getIntent().getStringExtra(Constants.STR_PHONE);
        if (!StringUtils.isNull(mTempPhone)) {
            etPhone.setText(mTempPhone);
            etPhone.setSelection(etPhone.getText().toString().trim().length());
        }
        tvTips.setText(AppChangeUtils.LOGIN_TEXT);
        tvTips.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);//下划线
        tvTips.getPaint().setAntiAlias(true);//抗锯齿
        tvTips.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, WebViewActivity.class);
                intent.putExtra("title", ((TextView) v).getText());
                intent.putExtra("url", Cons.cooperationUrl);
                startActivity(intent, false);
            }
        });
    }

    private void initData() {
        mFunction=getIntent().getStringExtra(Constants.KEY_LOGIN_FUN);
    }

    @Override
    protected void setListener() {

    }

    @Override
    protected void processLogic() {

    }

    /**
     * 表单验证
     */
    private boolean verification() {
        phone = etPhone.getText().toString().trim();
        phone= StringUtils.removeAllSpace(phone);
        password = etPassword.getText().toString().trim();
        if (!RegexUtils.isMobileSimple(phone)) {
            ToastUtil.showToast(mContext, "请输入正确的手机号");
            return false;
        } else if ("".equals(password)) {
            ToastUtil.showToast(mContext, "请输入密码");
            return false;
        } else {
            return true;
        }
    }

    @OnClick(R.id.btn_login)
    public void onClick() {
        if (verification()) {
            String pass = MD5.MD5Encode(new StringBuffer(password).toString());
            loadingView.show();
            IUserService.login(this, phone, pass, null,false, new ObjectCallback<String>() {
                @Override
                public void onSuccess(String response, String message) {
                    dialogDis();
                    if (StringUtils.isNull(response) || "null".equals(response)) {
                        ToastUtil.showToast(mContext, "登录失败");
                        return;
                    }
                    DataCenter.getInstance().setToken(response);
                    //登录成功存储到本地
                    DataUtil.setSharePre(mContext, "token", response);
                    notifeMyinfo();
                    doJsFunction();
                    if (isToMain) {
                        startActivity(MainActivity.class, true);
                    } else {
                        onBackPressed();
                        EventBus.getDefault().post(new UiEvent(EventConstant.FLAG_LOGIN_PSW,null));
                    }
                    EventBus.getDefault().post(new UiEvent(EventConstant.FLAG_DO_REGIST_PUSH,null));
                }

                @Override
                public void onErrorT(int code, String response, String errorMessage) {
                    dialogDis();
                    Logger.e("login-----"+errorMessage);
                    ToastUtil.showToast(mContext, errorMessage);
                }

                @Override
                public void onHttpErrorCall(int statusCode) {
                    dialogDis();
                    Logger.e("login-----+statusCode"+statusCode);
                }
            });
        }
    }

    /**
     * js 回调 登录状态
     */

    private void doJsFunction() {
        if(StringUtils.isNull(mFunction)){
            return;
        }
        EventBus.getDefault().post(new UiEvent(EventConstant.FLAG_LOGIN_SUCCESS,mFunction));
    }


    @OnClick(R.id.yan_zhen)
    public void onToCodeLogin() {
        Intent intent=new Intent(mContext,CodeLoginActivity.class);
        intent.putExtra("isToMain",isToMain);
        startActivity(intent,false);
    }

    /**
     * 通知刷新我的信息
     */
    private void notifeMyinfo() {
        EventBus.getDefault().post(new UiEvent(EventConstant.S_MYINFO, ""));
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        hideKeyBoard(ev);//隐藏软键盘
        return super.dispatchTouchEvent(ev);
    }


    @Override
    protected void onDestroy() {
        //更新密码登录页面 手机框
        String mTempPhome=etPhone.getText().toString().trim();
        mTempPhome= StringUtils.removeAllSpace(mTempPhome);
        EventBus.getDefault().post(new UiEvent(EventConstant.FLAG_CHANGE_PHONE_NUM, mTempPhome));
        super.onDestroy();
        ActivityStack.getInstance().finishActivity(this);
        if(!DataCenter.getInstance().checkIsLogin()){//还没登录

        }
    }


}
